import React, { Component, createRef, useEffect, useState } from 'react';
import {
  View,
  Image,
  TouchableWithoutFeedback,
  Text,
  TextInput,
  FlatList,
  Keyboard,
  Pressable,
} from 'react-native';
import { TitleBar } from '../components';
import i18n from '../i18n';
import { chunkArray, RegExpArr } from '../utils/jsUtils';
import stylesXS from '../styles/xs';
import stylesMD from '../styles/md';
import stylesLG from '../styles/lg';
import { StickerListView } from 'react-native-sticker-lib/src/view/StickerListView';
import dimesA5 from '../styles/size/a5';
import dimesA5X2 from '../styles/size/a5x2';
import dimesA6 from '../styles/size/nom';
import jestConfig from '../../jest.config';
import { SNPluginManager } from 'rtn-supernote-plugin-core';

const blueKeyBoardHeight = 50;

let deviceType = null;
SNPluginManager.getDeviceType()
  .then(result => {
    deviceType = result;
  })
  .catch(error => {
    console.error("getDeviceType error", error);
  });

class StickerContentPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchName: '',
      pressBtn: false,
      isInputSpecial: false,// 是否输入特殊字符
      keyboardHeight:0, //键盘高度，列表高度需要扣除蓝牙键盘高度，否则整体布局会上移
      lastGroupId:'', // 上一个分组ID
    };
    this._renderItem = this._renderItem.bind(this);
    this.textInputRef = createRef();
    this.keyboardDidShowListener = null;
    this.keyboardDidHideListener = null;
    console.log("StickerContentPage deviceType:"+deviceType);
  }

  componentDidMount() {
    if (this.props.stickerGroupItem?.id === 'search') {
        this.focusTextInput();
    }
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      (e) => {
        if (deviceType >= 4) {
          return;
        }
        const keyboardHeight = e.endCoordinates.height;
        console.log("keyboardDidShow keybord height:" + e.endCoordinates.height);
        // 小于300表示是蓝牙键盘，需要设置列表高度，以防显示有误
        if (keyboardHeight < 300) {
          this.setState({ keyboardHeight: blueKeyBoardHeight });
        }
      }
    );

    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        if (deviceType >= 4) {
          return;
        }
        this.setState({ keyboardHeight: 0 });
      }
    );

  }

  componentWillUnmount() {
    this.keyboardDidShowListener?.remove();
    this.keyboardDidHideListener?.remove();
}

  static getSnapshotBeforeUpdate(prevProps, prevState) {
    if (this.props.stickerGroupItem?.id === 'search') {
      this.setState({
        searchName: prevState?.searchName,
        pressBtn: prevState?.pressBtn,
      });
      if (!prevState?.searchName) {
        setTimeout(() => {
          this.focusTextInput();
        }, 100);
      }
      if (prevState?.pressBtn) {
        prevProps.onSearch();
      }
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    var isRender =
      nextProps.stickerGroupItem !== this.props.stickerGroupItem ||
      nextProps.list !== this.props.list ||
      nextProps.headerStatus !== this.props.headerStatus ||
      nextProps.status !== this.props.status ||
      nextProps.screenHeight !== this.props.screenHeight ||
      nextProps.screenWidth !== this.props.screenWidth ||
      nextState.searchName !== this.state.searchName ||
      nextState.pressBtn !== this.state.pressBtn ||
      nextProps.moreVisible !== this.props.moreVisible ||
      nextProps.isContentLoading != this.props.isContentLoading ||
      nextProps.rotation != this.props.rotation ||
      nextState.isInputSpecial != this.state.isInputSpecial ||
      nextState.keyboardHeight != this.state.keyboardHeight;
    console.log(
      'StickerContentPage shouldComponentUpdate isRender:' + isRender );
    console.log("StickerContentPage shouldComponentUpdate list:"+
      (nextProps.list !== this.props.list)
    );
    if (isRender && this.props.stickerGroupItem?.id === 'search') {

      this.focusTextInput();
    }

    return isRender;
  }

  _renderItem = (item, index) => {
    return (
      <ItemView
        item={item}
        index={index}
        styles={this.styles}
        onItemPress={this.props.onItemPress}
        onCheckPress={this.props.onCheckPress}
        onItemLongPress={this.props.onItemLongPress}
        screenHeight={this.props.screenHeight}
        screenWidth={this.props.screenWidth}
        status={this.props.status}
        stickerGroupItem={this.props.stickerGroupItem}
        headerStatus={this.props.headerStatus}
      />
    );
  };

  handleSearchNameChange = searchName => {
    this.setState({ searchName });
  };

  handleSearch = () => {
    const { searchName } = this.state;
    this.props.onSearch(searchName);
    this.setState({ pressBtn: true });
  };

  focusTextInput = () => {
    console.log("focusTextInput this.textInputRef.current:"+this.textInputRef.current);
    if (this.textInputRef.current && !this.state.searchName) {
      requestAnimationFrame(() => {
          this.textInputRef?.current?.focus();
      });
    }
  };

  // 获取需要渲染的贴纸列表，主要是最近使用
  getRenderList = (list, isLandscape, stickerGroupItem, wd) =>{
    if(stickerGroupItem?.id === 'recent') {
      if(isLandscape) {
        const maxLength = wd == 1024 || wd == 1365 ? 30 : 24;
        if(list?.length > maxLength) {
          return list.slice(0, maxLength);
        } else {
          return list;
        }
      } else {
        const maxLength = wd == 1024 || wd == 1365 ? 28 
        : wd == 994 || wd == 1325
        ? 24 : 20;
        console.log("StickerContentPage getRenderList wd:"+wd +"=="+maxLength);
        if(list?.length > maxLength) {
          return list.slice(0, maxLength);
        } else {
          return list;
        }
      }

    }

    return list;
  }

  render() {
    const { searchName, pressBtn, isInputSpecial, keyboardHeight } = this.state;
    const {
      stickerGroupItem,
      list,
      onOpen,
      onItemPress,
      onItemLongPress,
      onCheckPress,
      onClearRecent,
      onSearch,
      setSearchNm,
      status,
      headerStatus,
      screenWidth,
      screenHeight,
      isContentLoading,
      rotation
    } = this.props;
    const isLandscape = screenWidth > screenHeight;
    let wd = Math.round(screenWidth);
    const styles =
      wd == 1024 || wd == 1365
        ? stylesLG
        : wd == 994 || wd == 1325
          ? stylesMD
          : stylesXS;
    const nom = wd === 1024 || wd === 1365
      ? dimesA5X2
      : wd === 994 || wd === 1325
        ? dimesA5
        : dimesA6;
    this.styles = styles;
    const renderList = this.getRenderList(list, isLandscape, stickerGroupItem, wd);
    console.log("StickerContentPage list:" + list.length);
    console.log("StickerContentPage isContentLoading:"+isContentLoading);
    console.log("StickerContentPage stickerGroupItem:"+stickerGroupItem?.id);
    console.log("StickerContentPage lastGroupId:"+this.state.lastGroupId);
    if(this.state.lastGroupId === '') {
      this.setState({ lastGroupId: stickerGroupItem?.id });
    }
    // 上一个分组ID不是是搜索，且搜索内容为空，置按钮为false
    if(this.state.lastGroupId !== 'search' && !searchName) { 
      this.state.pressBtn = false;
    } 
    console.log("StickerContentPage pressBtn:"+pressBtn+", searchName:"+searchName);
     this.setState({ lastGroupId: stickerGroupItem?.id });

    // 内容列表高度
    const contentListHeight = (stickerGroupItem?.id === 'search'
      ? screenHeight - styles.titleHeight.height - styles.searchBody.height
      - styles.searchBody.marginTop
      : screenHeight - styles.titleHeight.height * 2) - keyboardHeight;
      console.log("StickerContentPage keyboardHeight:"+keyboardHeight);
    return (
      <View
        style={{
          width:
            screenWidth -
            (screenWidth > screenHeight
              ? styles.width_456.width
              : styles.width_432.width),
          height: screenHeight - styles.titleHeight.height,
        }}>
        <View style={styles.paddingHor_48}>
          {stickerGroupItem?.id === 'search' ? (
            <View style={[styles.searchCard, styles.searchBody]}>
              <View>
                <TextInput
                  style={[
                    styles.textInputStyle,
                    {
                      width:
                        screenWidth -
                        (screenWidth > screenHeight
                          ? styles.width_456.width
                          : styles.width_432.width) -
                        styles.searchBtnSize.width -
                        styles.createClose.width * 2,
                    },
                    styles.searchInput,
                    { borderRightWidth: 0 },
                  ]}
                  contextMenuHidden={true}
                  caretHidden={true}
                  editable={true}
                  ref={this.textInputRef}
                  placeholder={i18n.t('placeholder.sticker')}
                  multiline={false}
                  numberOfLines={1}
                  onChangeText={e => {
                    const pattern = RegExpArr.special;
                    var matchTxt = e.match(pattern);
                    console.log("search test matchTxt:"+matchTxt);
                    if (matchTxt) {
                      e = e.replace(matchTxt[0], '');
                      console.log("search test matchTxt[0]:"+matchTxt[0] +"=="+e);
                      this.setState({ isInputSpecial: true });
                      setTimeout(() => {
                        this.setState({ isInputSpecial: false });
                      }, 3000);
                    }
                    if(!e) {
                      // this.state.pressBtn = false;
                    }
                    
                    this.setState({ searchName: e });
                    setSearchNm(e);
                  }}
                  onBlur={() => {
                    Keyboard.dismiss();
                  }}
                  // maxLength={150}
                  value={searchName}
                />
                {this.state.isInputSpecial ? (
                  <View
                    style={[
                      styles.modalTextInputCard,
                      {
                        position: 'absolute',
                        marginStart: 0,
                        marginTop: 0,
                        width: '100%',
                        height: '100%',
                      }
                    ]}
                  >
                    <Text
                      style={[
                        styles.modalTextInputCard,
                        styles.fontSize_34,
                        styles.paddingRl_20_20,
                        {
                          position: 'absolute',
                          marginStart: 0,
                          marginTop: 0,
                          width: '100%',
                          height: '100%',
                          fontWeight: '400',
                          color: '#fff',
                          backgroundColor: 'black',
                          textAlignVertical: 'center',
                        }

                      ]}
                    >{i18n.t('msg.specialToast')}</Text>
                  </View>
                ) : null}
              </View>
              {searchName ? (
                <TouchableWithoutFeedback
                  onPress={e => {
                    // this.state.pressBtn = false;
                    this.setState({ searchName: '' });
                  }}>
                  <Image
                    style={styles.clearBtn}
                    source={require('../../assets/ic_close.png')}
                  />
                </TouchableWithoutFeedback>
              ) : null}
              {searchName ? (
                <TouchableWithoutFeedback
                  onPress={() => {
                    console.log('StickerContentPage search Press');
                    searchName ? onSearch(searchName) : null;
                    this.state.pressBtn = true;
                    Keyboard.dismiss();
                  }}>
                  <View
                    style={[
                      styles.searchBtnSize,
                      styles.searchBtn,
                      searchName ? null : { backgroundColor: '#999' },
                    ]}>
                      <Image
                      style={[styles.checkBtnWH,
                        {resizeMode: 'contain'}
                      ]}
                      source={require('../../assets/ic_search_white.png')}
                    />
                    {/* <Text
                      style={[
                        styles.textFont,
                        styles.fontSize_34,
                        { color: '#fff' },
                      ]}>
                      {i18n.t('btn.search')}
                    </Text> */}
                  </View>
                </TouchableWithoutFeedback>
              ) : (
                <View
                  style={[
                    styles.searchBtnSize,
                    styles.searchBtn,
                    searchName ? null : { backgroundColor: '#999' },
                  ]}>
                    <Image
                      style={[styles.checkBtnWH,
                        {resizeMode: 'contain'}
                      ]}
                      source={require('../../assets/ic_search_white.png')}
                    />
                  {/* <Text
                    style={[
                      styles.textFont,
                      styles.fontSize_34,
                      { color: '#fff' },
                    ]}>
                    {i18n.t('btn.search')}
                  </Text> */}
                </View>
              )}
            </View>
          ) : (
              <TitleBar
              subTitle={true}
                title={stickerGroupItem?.isDefault
                  ? stickerGroupItem?.langName
                  : stickerGroupItem?.name}
              leftBtnStatus={false}
              rightBtnStatus={
                (stickerGroupItem?.id !== 'recent' && !stickerGroupItem?.isDefault) ||
                (list?.length > 0 && stickerGroupItem?.id === 'recent' && !isContentLoading)
              }
              backgroundColor={'#fff'}
              textColor={'#000'}
              rightBtnText={
                stickerGroupItem?.id === 'recent' && list?.length > 0
                  ? i18n.t('btn.clear')
                  : ''
              }
              rightBtnTextStyle={styles.bottomBorder}
              status={'content'}
              screenWidth={screenWidth}
              screenHeight={screenHeight}
              onRight={() => {
                stickerGroupItem?.id === 'recent' ? onClearRecent() : onOpen();
              }}
              sWidth={{
                width:
                  screenWidth -
                  (screenWidth > screenHeight
                    ? styles.width_456.width
                    : styles.width_432.width) -
                  styles.clearBtn.width * 2,
              }}
            />
          )}
        </View>
        <View
          style={[
            styles.flexCenterWrap,
            {
              height:contentListHeight,
            },
          ]}>
          <StickerListView
            style={{
              height: contentListHeight,
              width:
                screenWidth -
                (screenWidth > screenHeight
                  ? styles.width_456.width
                  : styles.width_432.width) -
                2,
            }}
            rotation={rotation}
            dataList={renderList}
            scrollEnable={stickerGroupItem?.id !== 'recent' }
            itemClick={(event) => {
              console.log("StickerContentPage StickerListView itemClick:" + event.nativeEvent.id);
              var item = renderList.find(item => item.id === event.nativeEvent.id);
              console.log("StickerContentPage StickerListView  item:" + JSON.stringify(item));
              if (item != undefined && item != null) {
                if (!stickerGroupItem?.isDefault) {
                  if (headerStatus) {
                    onItemPress(item);
                  } else {
                    item.status = !item.status;

                    onCheckPress(item);
                  }
                } else {
                  onItemPress(item);
                }
              }


            }}
            itemLongClick={(event) => {
              if (!stickerGroupItem?.isDefault) {
                // console.log('StickerContent ItemView onLongPress');
                if (status != 'search' && status != 'recent') {
                  var item = renderList.find(item => item.id === event.nativeEvent.id);
                  item.status = true;
                  onItemLongPress(item);
                }
              }

            }}
            isEdit={status === 'content' && !headerStatus}

          />

          {isContentLoading ?(
             <View
                      style={{
                        width: '100%',
                        height:  contentListHeight,
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        zIndex: 9999,
                        backgroundColor: '#ffffff',
                      }}
                    />
          ) :
          
          list?.length === 0 ?(<View
            style={{

              position: 'absolute',

              marginTop: 0,
              marginStart: 0,
              alignItems: 'center',
              paddingTop: screenHeight * 0.3,
              height: contentListHeight,
              width:
                screenWidth -
                (screenWidth > screenHeight
                  ? styles.width_456.width
                  : styles.width_432.width) -
                2,

            }}>
            {stickerGroupItem?.id === 'search' &&
              // searchName &&
              pressBtn &&
              list?.length === 0 ? (
              <View
                style={[
                  styles.justAlign,
                  {
                    width: screenWidth * 0.5,
                  },
                ]}>
                <Image
                  style={styles.emptyImg}
                  source={require('../../assets/ic_search_not_find.png')}
                />
                <Text
                  style={[
                    styles.textFont,
                    styles.fontSize_34,
                    styles.marginVertical_24,
                    {
                      fontWeight:'700',
                    }
                  ]}>
                  {i18n.t('msg.res')}
                </Text>
                <Text style={[styles.fontSize_30, { fontWeight: '400' }]}>
                  {i18n.t('msg.otherTerm')}
                </Text>
              </View>
            ) : null}
            {stickerGroupItem?.id === 'recent' && list?.length === 0 ? (
              <View style={[styles.justAlign, { width: screenWidth * 0.5 }]}>
                <Image
                  style={styles.emptyImg}
                  source={require('../../assets/ic_sticker-think.png')}
                />
                <Text
                  style={[
                    styles.textFont,
                    styles.fontSize_34,
                    styles.marginVertical_24,
                    {
                      fontWeight:'700'
                    }
                  ]}>
                  {i18n.t('msg.recentRes')}
                </Text>
              </View>
            ) : null}
            {stickerGroupItem?.id !== 'recent' &&
              stickerGroupItem?.id !== 'search' &&
              list?.length === 0 ? (
              <View style={[styles.justAlign, { width: screenWidth * 0.5 }]}>
                <Image
                  style={styles.emptyImg}
                  source={require('../../assets/ic_sticker-think.png')}
                />
                <Text
                  style={[
                    styles.textFont,
                    styles.fontSize_34,
                    styles.marginVertical_24,
                    {
                      fontWeight:'700',
                      marginBottom: nom.dp_px_10
                    }
                  ]}>
                  {i18n.t('msg.resYet')}
                </Text>
                <Text
                  style={[
                    styles.fontSize_30,
                    {
                      fontWeight: '400',
                      width: screenWidth * 0.5,
                      textAlign: 'center',
                      height: nom.dp_px_200,
                      
                    },
                  ]}>
                  {i18n.t('msg.tap')}
                  <Image
                    style={[
                      styles.checkBtnWH,
                      {
                        resizeMode: 'contain',
                      },
                    ]}
                    source={require('../../assets/ic_lasso.png')}
                  />
                  {i18n.t('msg.tapAnd')}        
                  <Image
                    style={[
                      styles.checkBtnWH,
                      {
                        resizeMode: 'stretch',
                      },
                    ]}
                    source={require('../../assets/ic_sticker.png')}
                  />           
                  {i18n.t('msg.tapEnd')}
                </Text>
              </View>
            ) : null}
          </View>):null}

          {/* <FlatList
            data={chunkArray(list, isLandscape ? 6 : 4)}
            renderItem={({item}) => {
              return (
                <View style={styles.flexCenterWrap}>
                  {item && item.map((ite, indx) => this._renderItem(ite, indx))}
                </View>
              );
            }}
            initialNumToRender={7}
            windowSize={3}
            showsVerticalScrollIndicator={true}
            contentContainerStyle={[
              {
                width:
                  screenWidth -
                  (screenWidth > screenHeight
                    ? styles.width_456.width
                    : styles.width_432.width) -
                  2,
              },
              styles.paddingHor_48,
            ]}
            keyExtractor={(item, index) => index.toString()}
            decelerationRate={0}
            ListEmptyComponent={() => (
              <View
                style={{
                  flex: 1,
                  flexDirection: 'row',
                  justifyContent: 'center',
                  alignItems: 'center',
                  paddingTop: screenHeight * 0.3,
                }}>
                {stickerGroupItem?.id === 'search' &&
                searchName &&
                pressBtn &&
                list?.length === 0 ? (
                  <View
                    style={[
                      styles.justAlign,
                      {
                        width: screenWidth * 0.5,
                      },
                    ]}>
                    <Image
                      style={styles.emptyImg}
                      source={require('../../assets/ic_search_not_find.png')}
                    />
                    <Text
                      style={[
                        styles.textFont,
                        styles.fontSize_34,
                        styles.marginVertical_24,
                      ]}>
                      {i18n.t('msg.res')}
                    </Text>
                    <Text style={[styles.fontSize_30, {fontWeight: '400'}]}>
                      {i18n.t('msg.otherTerm')}
                    </Text>
                  </View>
                ) : null}
                {stickerGroupItem?.id === 'recent' && list?.length === 0 ? (
                  <View style={[styles.justAlign, {width: screenWidth * 0.5}]}>
                    <Image
                      style={styles.emptyImg}
                      source={require('../../assets/ic_sticker-think.png')}
                    />
                    <Text
                      style={[
                        styles.textFont,
                        styles.fontSize_34,
                        styles.marginVertical_24,
                      ]}>
                      {i18n.t('msg.recentRes')}
                    </Text>
                  </View>
                ) : null}
                {stickerGroupItem?.id !== 'recent' &&
                stickerGroupItem?.id !== 'search' &&
                list?.length === 0 ? (
                  <View style={[styles.justAlign, {width: screenWidth * 0.5}]}>
                    <Image
                      style={styles.emptyImg}
                      source={require('../../assets/ic_sticker-think.png')}
                    />
                    <Text
                      style={[
                        styles.textFont,
                        styles.fontSize_34,
                        styles.marginVertical_24,
                      ]}>
                      {i18n.t('msg.resYet')}
                    </Text>
                    <Text
                      style={[
                        styles.fontSize_30,
                        {
                          fontWeight: '400',
                          width: screenWidth * 0.5,
                          textAlign: 'center',
                        },
                      ]}>
                      {i18n.t('msg.tap')}
                      <Image
                        style={[
                          styles.checkBtnWH,
                          {
                            resizeMode: 'contain',
                          },
                        ]}
                        source={require('../../assets/ic_lasso.png')}
                      />
                      {i18n.t('msg.tapAnd')}
                      <Image
                        style={[
                          styles.checkBtnWH,
                          {
                            resizeMode: 'contain',
                          },
                        ]}
                        source={require('../../assets/ic_sticker.png')}
                      />
                      {i18n.t('msg.tapEnd')}
                    </Text>
                  </View>
                ) : null}
              </View>
            )}
          /> */}
        </View>
      </View>
    );
  }
}


const ItemView = ({
  item,
  index,
  styles,
  onItemPress,
  onCheckPress,
  onItemLongPress,
  screenWidth,
  screenHeight,
  status,
  stickerGroupItem,
  headerStatus,
}) => {
  // 是否选中
  const [isSelected, setSelected] = useState(item.status);
  let wd = Math.round(screenWidth);

  useEffect(() => {
    setSelected(item.status);
  }, [item.status]);
  // console.log('StickerContent ItemView item:' + item?.name);

  return (
    <View style={styles.justAlign}>
      <TouchableWithoutFeedback
        onPress={() => {
          // console.log('StickerContent ItemView press');
          if (!stickerGroupItem?.isDefault) {
            if (headerStatus) {
              onItemPress(item);
            } else {
              item.status = !item.status;
              setSelected(item.status);
              onCheckPress(item);
            }
          } else {
            onItemPress(item);
          }
        }}
        onPressIn={() => {
          // console.log('StickerContent ItemView onPressIn');
        }}
        onLongPress={() => {
          if (!stickerGroupItem?.isDefault) {
            // console.log('StickerContent ItemView onLongPress');
            if (status != 'search' && status != 'recent') {
              item.status = !item.status;
              setSelected(item.status);
              onItemLongPress(item);
            }
          }
        }}
        delayLongPress={300}>
        <View
          style={[
            styles.justAlign,
            styles.contentItem,
            screenWidth > screenHeight
              ? styles.marginRight48
              : styles.marginRight52,
            (screenWidth < screenHeight && index % 4 === 3) ||
              (screenWidth > screenHeight && index % 6 === 5)
              ? { marginRight: 0 }
              : null,
          ]}>
          <View style={styles.justAlign}>
            <Image
              style={[
                styles.cardItemImg,
                {
                  resizeMode: 'contain',
                  resizeMethod: 'resize',
                },
              ]}
              source={
                item?.id === 'new_create_group'
                  ? require('../../assets/ic_add_group.png')
                  : !item?.thumb_sticker
                    ? require('../../assets/ic_sticker-think.png')
                    : { uri: `file://${item?.thumb_sticker}` }
              }
            />
          </View>
          <Text      
            style={[
              styles.cardItemText,
              {
                fontWeight: '400',
                textAlign: 'center',
              },
            ]}
            ellipsizeMode={'middle'}
            numberOfLines={1}
            maxLength={150}>
            {item?.isDefault ? item?.langName : item?.name}
          </Text>
          {status === 'content' && !headerStatus ? (
            <View style={styles.checkBtn}>
              <Image
                style={[
                  styles.checkBtnWH,
                  {
                    resizeMode: 'contain',
                  },
                ]}
                source={
                  item.status
                    ? require('../../assets/ic_select_black.png')
                    : require('../../assets/ic_select_no.png')
                }
              />
            </View>
          ) : null}
        </View>
      </TouchableWithoutFeedback>
    </View>
  );
};

export default StickerContentPage;
